<template>
  <div class="lab-applied-summary-sheet">
    <div class="title mb-10">
      <Divider style="margin-top: 10px;">
        <h3 style="text-align: center;color: #17233d;">
          <span v-if="filter.studyYear">{{ filter.studyYear }} ~ {{ Number(filter.studyYear) + 1}}学年</span>
          <span v-if="filter.semester !== ''">第{{['一', '二'][filter.semester]}}学期</span>
          <span>实验室申请汇总表</span>
        </h3>
      </Divider>
    </div>
    <div class="top-toolbar pr-10 pl-10">
      <Row type="flex" :gutter="24" align="middle" class="position-relative">
        <Col :xs="24" :sm="24" :md="{span: 12}" :lg="6" class="mb-15">
          <span style="margin-right: 14px;">学期：</span>
          <Select style="width: calc(100% - 56px);"
                  :size="selectSize"
                  v-model="semesterString"
                  :enabledPreventOverflow="enabledPreventOverflow"
                  placeholder="请选择学期进行检索"
                  filterable
                  @on-change="onChangeSemester">
            <Option v-for="(item, index) in semesters" :value="item" :key="index">{{ item.split('/', 2)[0] }} ~ {{ Number(item.split('/', 2)[0]) + 1 }}学年第{{ ['一', '二'][item.split('/', 2)[1]] }}学期</Option>
          </Select>
        </Col>
        <Col :xs="24" :sm="24" :md="{span: 12}" :lg="7" class="mb-15">
          <span style="margin-right: 14px;">学院：</span>
          <div style="display: inline-block;width: calc(100% - 56px);">
            <Select
              v-if="userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN', 'ROLE_TEACHER', 'ROLE_STUDENT_ASSISTANT'].indexOf(item) > -1 })"
              :size="selectSize"
              v-model="filter.institute"
              :enabledPreventOverflow="enabledPreventOverflow"
              placeholder="请选择学院进行检索"
              filterable
              @on-change="onChangeInstitute">
              <Option v-for="(item, index) in institutes" :value="item" :key="index">{{ item }}</Option>
            </Select>
            <Input v-else v-model="filter.institute" readonly placeholder="当前学院"/>
          </div>
        </Col>
        <Col :xs="24" :sm="24" :md="{span: 12}" :lg="7" class="mb-15">
          <span>实验室：</span>
          <div style="display: inline-block;width: calc(100% - 56px);">
            <Select v-model="filter.labCode"
                    :size="selectSize"
                    :enabledPreventOverflow="enabledPreventOverflow"
                    :placeholder="filter.institute ? '请选择实验室进行检索' : '请先选择学院'"
                    :disabled="!filter.institute"
                    filterable
                    :loading="selectLoading"
                    loading-text="查询实验室中，请稍等"
                    @on-change="onChangeLab">
              <Option value="all" key="all">全部</Option>
              <Option v-for="item in labs" :value="item.code" :key="item.code" :label="item.code + '  丨  ' + item.name"
                      :disabled="!'ACTIVATING'===item.status">
                <span>{{ item.code }}</span>
                <span style="float:right;color:#ccc">{{ item.name }}</span>
              </Option>
            </Select>
          </div>
        </Col>
        <Col :xs="24" :sm="16" :md="{span: 5, offset: 7}" :lg="3" class="btn-container mb-15"
             v-if="this.userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN'].indexOf(item) > -1 })">
          <Tooltip>
            <Button class="export-btn" @click="exportAllToExcel" :loading="exportLoading" :size="btnSize">
              <font-awesome-icon icon="file-excel" v-if="!exportLoading" />
              导出全部
            </Button>
            <div slot="content">
              <p>当前检索条件下，</p>
              <p>不分页的全部导出</p>
            </div>
          </Tooltip>
        </Col>
      </Row>
    </div>
    <div class="table-container small-table">
      <Table :border="table.showBorder"
             :stripe="table.showStripe"
             :show-header="table.showHeader"
             :height="table.fixedHeader ? table.height : ''"
             :size="table.size"
             :data="table.data"
             :columns="table.columns"
             :loading="table.loading"
             :disabledHover="table.disabledHover"
             :highlight-row="table.highlightRow">
        <template slot-scope="{ row, index }" slot="laboratory">
          <span v-for="(item, index) in row.classroom" :key="index">
            <span
              v-if="item.institute">{{ item.institute }}&nbsp; -<br/></span>{{ item.name }}&nbsp; -<br/>{{ item.code }}
              <span v-if="index !== row.classroom.length - 1">
                <span class="d-none">**</span>
                <Divider style="margin-top: 10px; margin-bottom: 10px;"/>
                <span class="d-none">**</span>
              </span>
          </span>
        </template>
        <template slot-scope="{ row, index }" slot="cGrade">
          <span v-for="(item, index) in row.cGrade.content" :key="index">
            <span>{{ item || '无'}}</span>
            <span v-if="index !== row.cGrade.content.length - 1">
              <span class="d-none">##</span>
              <Divider style="margin-top: 10px; margin-bottom: 10px;"/>
            </span>
          </span>
        </template>
        <template slot-scope="{ row, index }" slot="cInstitute">
          <span v-for="(item, index) in row.cInstitute.content" :key="index">
            <span>{{ item || '无'}}</span>
            <span v-if="index !== row.cInstitute.content.length - 1">
              <span class="d-none">##</span>
              <Divider style="margin-top: 10px; margin-bottom: 10px;"/>
            </span>
          </span>
        </template>
        <template slot-scope="{ row, index }" slot="cMajor">
          <span v-for="(item, index) in row.cMajor.content" :key="index">
            <span>{{ item || '无'}}</span>
            <span v-if="index !== row.cMajor.content.length - 1">
              <span class="d-none">##</span>
              <Divider style="margin-top: 10px; margin-bottom: 10px;"/>
            </span>
          </span>
        </template>
        <template slot-scope="{ row, index }" slot="cSclass">
          <span v-for="(item, index) in row.cSclass.content" :key="index">
            <span>{{ item || '无'}}</span>
            <span v-if="index !== row.cSclass.content.length - 1">
              <span class="d-none">##</span>
              <Divider style="margin-top: 10px; margin-bottom: 10px;"/>
            </span>
          </span>
        </template>
        <template slot-scope="{ row, index }" slot="expTime">
        <span v-for="(item, index) in row.trainingExpTime" :key="index">
          {{ item.dates.join(' ~ ') }}
          <span v-if="typeof item.haveClassOnWeekend !== 'undefined'">
            <br/>
            (周末{{ item.haveClassOnWeekend ? '' : '不' }}上课)
          </span>
        </span>
        </template>
      </Table>
    </div>
    <div class="pagination text-right pr-15 mt-20">
      <Page :current="pageBuilder.pageNum"
            :size="page.size"
            :total="page.total"
            :page-size="page.pageSize"
            :page-size-opts="page.pageSizeOpts"
            :show-sizer="page.showSizer"
            :simple="page.simple"
            :show-elevator="page.showElevator"
            :show-total="page.showTotal"
            @on-change="onPageNumChange"
            @on-page-size-change="onPageSizeChange"/>
    </div>
    <LabAppliedSummarySheet ref="labAppliedSummarySheet" class="child-table d-none" v-if="exportAll" @start-export="startExport" />
  </div>
</template>

<script>
import {mapActions} from 'vuex'
import {
  getInstituteList,
  getLabListByInstitute,
  getCurrTermDateInfo,
  getFirstWeekDateList,
  getLabAppliedSummarySheet
} from '@/api/lab-applied-summary-sheet'
import { trim, activeTableMove } from '@/libs/tools'
import { s2ab } from '@/libs/excel'
import {library} from '@fortawesome/fontawesome-svg-core'
import {faFileExcel} from '@fortawesome/free-solid-svg-icons'
library.add(faFileExcel)
export default {
  name: 'LabAppliedSummarySheet',
  data () {
    return {
      btnSize: 'default',
      selectSize: 'default',
      selectLoading: false,
      enabledPreventOverflow: false,
      filter: {
        studyYear: '',
        semester: '',
        institute: '',
        labCode: 'all'
      },
      semesters: [],
      semesterString: '',
      userAccess: [],
      institutes: [],
      labs: [],
      table: {
        showBorder: true,
        showStripe: false,
        showHeader: true,
        fixedHeader: true,
        height: '',
        disabledHover: true,
        size: 'small',
        loading: false,
        columns: [{
          title: '序号',
          width: 40,
          key: 'index',
          align: 'center',
          className: 'row-combined',
          render: (h, params) => {
            return h('span', params.row.index.content)
          }
        }, {
          title: '类别',
          width: 55,
          key: 'expType',
          align: 'center',
          render: (h, params) => {
            const row = params.row
            const color = row.expType.content === 'TRAINING' ? 'cyan' : 'blue'
            const text = row.expType.content === 'TRAINING' ? '实训' : '普通'
            return h('Tag', {
              props: {
                color: color
              },
              style: {
                marginRight: '0'
              }
            }, text)
          },
          className: 'row-combined'
        }, {
          title: '教师名称',
          key: 'teacherName',
          width: 75,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.teacherName.content || '无')
          },
          className: 'row-combined'
        }, {
          title: '课程名称',
          key: 'courseName',
          minWidth: 120,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.courseName.content || '无')
          },
          className: 'row-combined'
        }, {
          title: '课程类别',
          key: 'courseType',
          width: 70,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.courseType.content || '无')
          },
          className: 'row-combined'
        }, {
          title: '实验教材',
          key: 'textbook',
          minWidth: 120,
          align: 'center',
          tooltip: true,
          render: (h, params) => {
            return h('span', params.row.textbook.content || '无')
          },
          className: 'row-combined'
        }, {
          title: '实验编号',
          key: 'expIndex',
          width: 40,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.expIndex.content)
          },
          className: 'row-combined'
        }, {
          title: '实验名称',
          key: 'title',
          minWidth: 120,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.title.content || '无')
          },
          className: 'row-combined'
        }, {
          title: '实验类型',
          key: 'type',
          width: 90,
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.type.content || '无')
          },
          className: 'row-combined'
        }, {
          title: '实验时间',
          align: 'center',
          children: [
            {
              title: '周次',
              key: 'sweek',
              width: 45,
              className: 'row-combined',
              align: 'center'
            }, {
              title: '星期',
              key: 'sdate',
              width: 45,
              className: 'row-combined',
              align: 'center'
            }, {
              title: '节次',
              key: 'section',
              width: 80,
              align: 'center',
              className: 'row-combined',
              render: (h, params) => {
                return h('span', params.row.section ? params.row.section.join('、') : '/')
              }
            }, {
              title: '日期',
              slot: 'expTime',
              key: 'trainingExpTime',
              width: 90,
              className: 'row-combined',
              align: 'center'
            }
          ]
        }, {
          title: '实验室',
          slot: 'laboratory',
          key: 'classroom',
          minWidth: 170,
          align: 'center',
          className: 'row-combined'
        }, {
          title: '计划学时',
          key: 'planHours',
          width: 40,
          align: 'center',
          className: 'row-combined',
          render: (h, params) => {
            return h('span', params.row.planHours.content || '无')
          }
        }, {
          title: '实际学时',
          key: 'actualHours',
          width: 40,
          align: 'center',
          className: 'row-combined',
          render: (h, params) => {
            return h('span', params.row.actualHours.content || '无')
          }
        }, {
          title: '耗材需求',
          key: 'resources',
          minWidth: 100,
          align: 'center',
          className: 'row-combined',
          render: (h, params) => {
            return h('span', params.row.resources.content || '无')
          }
        }, {
          title: '软件需求',
          key: 'software',
          minWidth: 100,
          align: 'center',
          className: 'row-combined',
          render: (h, params) => {
            return h('span', params.row.software.content || '无')
          }
        }, {
          title: '系统需求',
          key: 'system',
          minWidth: 100,
          align: 'center',
          className: 'row-combined',
          render: (h, params) => {
            return h('span', params.row.system.content || '无')
          }
        }, {
          title: '教学对象',
          align: 'center',
          children: [
            {
              title: '学院',
              key: 'cInstitute',
              minWidth: 140,
              align: 'center',
              className: 'row-combined',
              slot: 'cInstitute'
            }, {
              title: '年级',
              key: 'cGrade',
              width: 55,
              align: 'center',
              className: 'row-combined',
              slot: 'cGrade'
            }, {
              title: '专业',
              key: 'cMajor',
              minWidth: 110,
              align: 'center',
              tooltip: true,
              className: 'row-combined',
              slot: 'cMajor'
            }, {
              title: '班级',
              key: 'cSclass',
              width: 50,
              align: 'center',
              className: 'row-combined',
              slot: 'cSclass'
            }, {
              title: '人数',
              key: 'stuNum',
              width: 50,
              align: 'center',
              className: 'row-combined',
              render: (h, params) => {
                return h('span', params.row.stuNum.content || '无')
              }
            }
          ]
        }],
        data: [],
        highlightRow: false
      },
      page: {
        size: 'small',
        total: 0,
        pageSize: 5,
        showSizer: true,
        showElevator: true,
        showTotal: true,
        pageSizeOpts: [5, 10, 20, 30, 40, 50],
        simple: false
      },
      pageBuilder: {
        pageSize: 5,
        pageNum: 1,
        sort: 'id',
        dir: 'desc'
      },
      exportLoading: false,
      exportAll: false
    }
  },
  methods: {
    ...mapActions([
      'getUserInfo'
    ]),
    onChangeInstitute (value) {
      if (!value) {
        this.filter.institute = ''
        this.filter.labCode = ''
        this.labs = []
        this.table.data = []
      } else {
        this.filter.institute = value
        this.filter.labCode = 'all'
        this.selectLoading = true
        getLabListByInstitute(value).then(res => {
          if (res.data.code === 1) {
            this.labs = res.data.data.length > 0 ? res.data.data.map(item => {
              return {
                'name': item.name,
                'code': item.code,
                'status': item.status
              }
            }) : []
            this.$nextTick(() => {
              this.selectLoading = false
            })
          } else {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取实验室列表失败！' + res.data.info
            })
          }
        }).catch(error => {
          this.selectLoading = false
          this.$Notice.error({
            title: '获取列表失败',
            desc: '获取实验室列表失败！'
          })
          console.log(error)
        })
      }
    },
    onChangeSemester (value) {
      if (value) {
        this.filter.studyYear = value.split('/', 2)[0]
        this.filter.semester = value.split('/', 2)[1]
      } else {
        this.filter.studyYear = ''
        this.filter.semester = ''
        this.table.data = []
      }
    },
    onChangeLab (value) {
      this.filter.labCode = value
    },
    // 页码改变的回调，返回改变后的页码
    onPageNumChange (value) {
      this.pageBuilder.pageNum = value
    },
    // 切换每页条数时的回调，返回切换后的每页条数
    onPageSizeChange (value) {
      this.pageBuilder.pageNum = 1
      this.pageBuilder.pageSize = value
    },
    getTableColumns (columns) {
      let tableColumns = []
      columns.forEach(item => {
        if (!item.children) {
          tableColumns.push(item)
        }
        if (item.children && item.children.length > 0) {
          tableColumns = tableColumns.concat(this.getTableColumns(item.children))
        }
      })
      return tableColumns
    },
    handleTableData (data, dIndex) {
      let tempData = []
      let rowSpan = 0
      data.expBaseInfoItems.forEach((item, eIndex) => {
        if (data.exp_type === 'COURSE' && item.expTimeItemsCourse && item.expTimeItemsCourse.length > 0) {
          let tempMap = new Map()
          item.expTimeItemsCourse.forEach((c, cIndex) => {
            if (!tempMap.has(c.index)) {
              tempMap.set(c.index, {
                sweek: c.expItemTime.sweek,
                sdate: c.expItemTime.sdate,
                section: new Set().add(c.expItemTime.section),
                classroom: new Set().add(JSON.stringify(c.classroom))
              })
            } else {
              tempMap.get(c.index).section.add(c.expItemTime.section)
              tempMap.get(c.index).classroom.add(JSON.stringify(c.classroom))
            }
          })
          item.expTimeItemsCourse = Array.from(tempMap)
          item.expTimeItemsCourse.forEach((c, cIndex) => {
            let obj = {
              index: {
                content: dIndex,
                rowSpan: 1,
                cellShow: false
              },
              expType: {
                content: data.exp_type,
                rowSpan: 1,
                cellShow: false
              },
              appCode: data.app_code,
              teacherName: {
                content: data.teacher_name,
                rowSpan: 1,
                cellShow: false
              },
              courseName: {
                content: data.course_name,
                rowSpan: 1,
                cellShow: false
              },
              courseType: {
                content: data.course_type,
                rowSpan: 1,
                cellShow: false
              },
              textbook: {
                content: data.textbook,
                rowSpan: 1,
                cellShow: false
              },
              stuNum: {
                content: data.stu_num,
                rowSpan: 1,
                cellShow: false
              },
              cInstitute: {
                content: Array.from(new Set(data.classes.map(item => {
                  return item.institute
                }))),
                rowSpan: 1,
                cellShow: false
              },
              cGrade: {
                content: Array.from(new Set(data.classes.map(item => {
                  return item.grade
                }))),
                rowSpan: 1,
                cellShow: false
              },
              cMajor: {
                content: Array.from(new Set(data.classes.map(item => {
                  return item.major
                }))),
                rowSpan: 1,
                cellShow: false
              },
              cSclass: {
                content: data.classes.map(item => {
                  return item.sclass
                }),
                rowSpan: 1,
                cellShow: false
              }
            }
            obj.expIndex = {
              content: eIndex + 1,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.sid = item.sid
            obj.title = {
              content: item.title,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.type = {
              content: item.type,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.actualHours = {
              content: item.actual_hours,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.planHours = {
              content: item.plan_hours,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.resources = {
              content: item.resources,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.software = {
              content: item.software,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj.system = {
              content: item.system,
              rowSpan: cIndex === 0 ? item.expTimeItemsCourse.length : 1,
              cellShow: cIndex === 0
            }
            obj = Object.assign({
              tIndex: cIndex,
              sweek: c[1].sweek,
              sdate: c[1].sdate,
              trainingExpTime: [{
                dates: ['/']
              }],
              section: Array.from(c[1].section),
              classroom: Array.from(c[1].classroom).map(cr => {
                return JSON.parse(cr)
              })
            }, obj)
            tempData.push(obj)
          })
          rowSpan = rowSpan + item.expTimeItemsCourse.length
        } else if (data.exp_type === 'TRAINING' && item.expTimeItemsTrain && item.expTimeItemsTrain.length > 0) {
          item.expTimeItemsTrain.forEach((c, cIndex) => {
            let obj = {
              index: {
                content: dIndex,
                rowSpan: 1,
                cellShow: false
              },
              expType: {
                content: data.exp_type,
                rowSpan: 1,
                cellShow: false
              },
              appCode: data.app_code,
              teacherName: {
                content: data.teacher_name,
                rowSpan: 1,
                cellShow: false
              },
              courseName: {
                content: data.course_name,
                rowSpan: 1,
                cellShow: false
              },
              courseType: {
                content: data.course_type,
                rowSpan: 1,
                cellShow: false
              },
              textbook: {
                content: data.textbook,
                rowSpan: 1,
                cellShow: false
              },
              stuNum: {
                content: data.stu_num,
                rowSpan: 1,
                cellShow: false
              },
              cInstitute: {
                content: Array.from(new Set(data.classes.map(item => {
                  return item.institute
                }))),
                rowSpan: 1,
                cellShow: false
              },
              cGrade: {
                content: Array.from(new Set(data.classes.map(item => {
                  return item.grade
                }))),
                rowSpan: 1,
                cellShow: false
              },
              cMajor: {
                content: Array.from(new Set(data.classes.map(item => {
                  return item.major
                }))),
                rowSpan: 1,
                cellShow: false
              },
              cSclass: {
                content: data.classes.map(item => {
                  return item.sclass
                }),
                rowSpan: 1,
                cellShow: false
              }
            }
            obj.expIndex = {
              content: eIndex + 1,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.sid = item.sid
            obj.title = {
              content: item.title,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.type = {
              content: item.type,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.actualHours = {
              content: item.actual_hours,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.planHours = {
              content: item.plan_hours,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.resources = {
              content: item.resources,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.software = {
              content: item.software,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj.system = {
              content: item.system,
              rowSpan: cIndex === 0 ? item.expTimeItemsTrain.length : 1,
              cellShow: cIndex === 0
            }
            obj = Object.assign({
              sweek: '/',
              sdate: '/',
              section: '',
              trainingExpTime: [{
                dates: c.dates,
                haveClassOnWeekend: c.haveClassOnWeekend
              }],
              tIndex: cIndex,
              classroom: c.classroom
            }, obj)
            tempData.push(obj)
          })
          rowSpan = rowSpan + item.expTimeItemsTrain.length
        }
      })
      tempData[0].index.rowSpan = rowSpan
      tempData[0].index.cellShow = true
      tempData[0].expType.rowSpan = rowSpan
      tempData[0].expType.cellShow = true
      tempData[0].teacherName.rowSpan = rowSpan
      tempData[0].teacherName.cellShow = true
      tempData[0].courseName.rowSpan = rowSpan
      tempData[0].courseName.cellShow = true
      tempData[0].courseType.rowSpan = rowSpan
      tempData[0].courseType.cellShow = true
      tempData[0].textbook.rowSpan = rowSpan
      tempData[0].textbook.cellShow = true
      tempData[0].stuNum.rowSpan = rowSpan
      tempData[0].stuNum.cellShow = true
      tempData[0].cInstitute.rowSpan = rowSpan
      tempData[0].cInstitute.cellShow = true
      tempData[0].cGrade.rowSpan = rowSpan
      tempData[0].cGrade.cellShow = true
      tempData[0].cMajor.rowSpan = rowSpan
      tempData[0].cMajor.cellShow = true
      tempData[0].cSclass.rowSpan = rowSpan
      tempData[0].cSclass.cellShow = true
      return tempData
    },
    async renderTable (filter, pageBuilder) {
      // 初始化表格
      this.table.loading = true
      this.table.data = []
      try {
        let response = await getLabAppliedSummarySheet(filter, pageBuilder)
        let res = response.data
        if (res.code === 1) {
          this.page.total = res.data.totalElements
          res.data.content.forEach((c, cIndex) => {
            this.table.data = this.table.data.concat(this.handleTableData(c, cIndex + 1))
            let columns = this.getTableColumns(this.table.columns)
            this.$nextTick(() => {
              this.$el.querySelector('.ivu-table-body').querySelectorAll('td.row-combined').forEach((item, index) => {
                let row = this.table.data[Math.floor(index / columns.length)]
                let cell = columns[index % columns.length].key
                if (Object.prototype.toString.call(row[cell]) === '[object Object]') {
                  item.setAttribute('rowspan', row[cell].rowSpan || 1)
                  item.style.display = row[cell].cellShow ? '' : 'none'
                }
              })
            })
          })
          this.$nextTick(() => {
            this.$el.querySelector('.ivu-table-body').querySelectorAll('td.row-combined').forEach((item, index) => {
              if (item.style.display === 'none') {
                item.parentNode.removeChild(item)
              }
            })
            this.$emit('start-export')
            this.table.loading = false
          })
        } else {
          this.table.loading = false
          this.table.data = []
          this.$Notice.error({
            title: '列表加载失败',
            desc: '实验室申请汇总表加载失败！' + res.info + '请重试！'
          })
        }
      } catch (error) {
        this.table.loading = false
        this.table.data = []
        this.$Notice.error({
          title: '列表加载失败',
          desc: '实验室申请汇总表加载失败！请重试！'
        })
        console.log(error)
      }
    },
    // exportToExcel: function () {
    //   this.exportLoading = true
    //   this.exportAll = true
    //   const table = document.querySelector('.lab-applied-summary-sheet .ivu-table')
    //   // 学年
    //   let title = this.filter.studyYear ? this.filter.studyYear + '~' + (Number(this.filter.studyYear) + 1) + '学年' : ''
    //   // 学期
    //   title += this.filter.semester !== '' ? '第' + ['一', '二'][this.filter.semester] + '学期-' : ''
    //   // 学院
    //   title += this.filter.institute ? this.filter.institute + '-' : ''
    //   // 实验室
    //   title += this.filter.labCode ? this.labs.filter(l => {
    //     return l.code === this.filter.labCode
    //   }).map(l => {
    //     return l.name + l.code
    //   }) + '-' : ''
    //   title += '实验室申请汇总表'
    //   const fileName = title
    //   const wb = this.$xlsx.utils.book_new()
    //   const ws = this.$xlsx.utils.table_to_sheet(table, {
    //     raw: true,
    //     display: true
    //   })
    //   // const border = {
    //   //   border: {
    //   //     top: {
    //   //       style: 'medium'
    //   //     },
    //   //     bottom: {
    //   //       style: 'medium'
    //   //     },
    //   //     left: {
    //   //       style: 'medium'
    //   //     },
    //   //     right: {
    //   //       style: 'medium'
    //   //     }
    //   //   }
    //   // }
    //   const center = {
    //     alignment: {
    //       vertical: 'center',
    //       wrapText: true,
    //       horizontal: 'center'
    //     }
    //   }
    //   // 遍历所有单元格进行样式的处理
    //   Object.keys(ws).forEach(k => {
    //     if (k !== '!merges' && k !== '!ref') {
    //       // 去掉内容前后所有的空格
    //       ws[k].v = trim(ws[k].v)
    //       // 把内容中间的所有**进行换行
    //       ws[k].v = ws[k].v.replace(/\*\*/g, '\n')
    //       // 把内容中间的所有##替换成、
    //       ws[k].v = ws[k].v.replace(/##/g, '、')
    //       // 添加center和border样式
    //       if (ws[k].v) {
    //         ws[k].s = {...center,
    //           ...{
    //             font: {
    //               name: 'Microsoft YaHei'
    //             }
    //           }
    //         }
    //       }
    //       if (ws[k].v === '暂无筛选结果') {
    //         delete ws[k]
    //       }
    //     }
    //   })
    //   this.$xlsx.utils.book_append_sheet(wb, ws, '实验室申请汇总表')
    //   const wbout = this.$xls.write(wb, {bookType: 'xlsx', type: 'binary'})
    //   this.$fileSaver.saveAs(new Blob([s2ab(wbout)], {type: ''}), fileName + '.xlsx')
    //   this.exportLoading = false
    // },
    exportAllToExcel () {
      this.exportLoading = true
      this.exportAll = true
      this.$nextTick(() => {
        this.$refs.labAppliedSummarySheet.filter = {...this.filter}
        this.$refs.labAppliedSummarySheet.pageBuilder.pageSize = 100000
      })
    },
    startExport () {
      const table = this.$refs.labAppliedSummarySheet.$el.querySelector('.ivu-table')
      // 学年
      let title = this.filter.studyYear ? this.filter.studyYear + '~' + (Number(this.filter.studyYear) + 1) + '学年' : ''
      // 学期
      title += this.filter.semester !== '' ? '第' + ['一', '二'][this.filter.semester] + '学期-' : ''
      // 学院
      title += this.filter.institute ? this.filter.institute + '-' : ''
      // 实验室
      title += this.filter.labCode && this.filter.labCode !== 'all' ? this.labs.filter(l => {
        return l.code === this.filter.labCode
      }).map(l => {
        return l.name + l.code
      }) + '-' : ''
      title += '实验室申请汇总表'
      const fileName = title
      const wb = this.$xlsx.utils.book_new()
      const ws = this.$xlsx.utils.table_to_sheet(table, {
        raw: true,
        display: true,
        ignoreEC: true
      })
      const center = {
        alignment: {
          vertical: 'center',
          wrapText: true,
          horizontal: 'center'
        }
      }
      // 遍历所有单元格进行样式的处理
      Object.keys(ws).forEach(k => {
        if (k !== '!merges' && k !== '!ref') {
          // 去掉内容前后所有的空格
          ws[k].v = trim(ws[k].v)
          // 把内容中间的所有**进行换行
          ws[k].v = ws[k].v.replace(/\*\*/g, '\n')
          // 把内容中间的所有##替换成、
          ws[k].v = ws[k].v.replace(/##/g, '、')
          // 添加center和border样式
          if (ws[k].v) {
            ws[k].s = {...center,
              ...{
                font: {
                  name: 'Microsoft YaHei'
                }
              }
            }
          }
          if (ws[k].v === '暂无筛选结果') {
            delete ws[k]
          }
        }
      })
      this.$xlsx.utils.book_append_sheet(wb, ws, '实验室申请汇总表')
      const wbout = this.$xls.write(wb, {bookType: 'xlsx', type: 'binary'})
      this.$fileSaver.saveAs(new Blob([s2ab(wbout)], {type: ''}), fileName + '.xlsx')
      this.exportLoading = false
      this.exportAll = false
    }
  },
  created () {
    this.firstEnter = true
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    // 获取当前学年和学期
    getCurrTermDateInfo().then(res => {
      if (res.data.code === 1) {
        this.filter.studyYear = res.data.data.studyYear
        this.filter.semester = res.data.data.semester
        this.semesterString = res.data.data.studyYear + '/' + res.data.data.semester
      } else {
        this.$Notice.error({
          title: '获取数据失败',
          desc: '获取当前学年、学期失败！' + res.data.info + '请重试！'
        })
      }
    }).catch(error => {
      console.log(error)
      this.$Notice.error({
        title: '获取数据失败',
        desc: '获取当前学年、学期失败！请重试！'
      })
    })
    // 获取历史学年和学期列表
    getFirstWeekDateList({
      pageSize: 1000,
      pageNum: 1,
      order: [{
        studyYear: 'desc'
      }, {
        semester: 'desc'
      }]
    }).then(res => {
      if (res.data.code === 1) {
        this.semesters = res.data.data.content.length > 0 ? res.data.data.content.map(item => {
          return item.studyYear + '/' + item.semester
        }) : []
      } else {
        this.$Notice.error({
          title: '列表加载失败',
          desc: '学期列表加载失败！' + res.data.info
        })
      }
    }).catch(error => {
      this.$Notice.error({
        title: '列表加载失败',
        desc: '学期列表加载失败！'
      })
      console.log(error)
    })
    // 获取用户信息
    this.getUserInfo().then(res => {
      if (res.data.code === 1) {
        res = res.data.data
        this.filter.institute = res.department || ''
        this.userAccess = res.roles || []
        if (this.userAccess.some(item => {
          return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN', 'ROLE_TEACHER', 'ROLE_STUDENT_ASSISTANT'].indexOf(item) > -1
        })) {
          // 获取所有学院
          getInstituteList().then(res => {
            if (res.data.code === 1) {
              this.institutes = res.data.data.length > 0 ? res.data.data : []
            } else {
              this.$Notice.error({
                title: '获取列表失败',
                desc: '获取学院列表失败！' + res.data.info
              })
            }
          }).catch(error => {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取学院列表失败！'
            })
            console.log(error)
          })
        }
        if (this.filter.institute) {
          getLabListByInstitute(this.filter.institute).then(res => {
            if (res.data.code === 1) {
              this.labs = res.data.data.length > 0 ? res.data.data.map(item => {
                return {
                  'name': item.name,
                  'code': item.code,
                  'status': item.status
                }
              }) : []
            } else {
              this.$Notice.error({
                title: '获取列表失败',
                desc: '获取实验室列表失败！' + res.data.info
              })
            }
          })
        }
      } else {
        this.$Notice.error({
          title: '获取信息失败',
          desc: '获取用户信息失败！' + res.info
        })
      }
    }).catch(error => {
      this.$Notice.error({
        title: '获取信息失败',
        desc: '获取用户信息失败！'
      })
      console.log(error)
    })
  },
  mounted () {
    this.$nextTick(() => {
      activeTableMove(document.querySelector('.lab-applied-summary-sheet .ivu-table-body'))
    })
  },
  activated () {
    if (!this.firstEnter) {
      this.$Notice.config({
        top: window.innerHeight / 3
      })
    }
  },
  deactivated () {
    this.firstEnter = false
    this.$Notice.destroy()
  },
  beforeDestroy () {
    this.$Notice.destroy()
  },
  watch: {
    filter: {
      handler: function (value) {
        if (value.studyYear && value.semester !== '' && value.institute) {
          this.pageBuilder.pageNum === 1 ? this.renderTable(value, this.pageBuilder) : this.pageBuilder.pageNum = 1
        } else {
          this.table.data = []
        }
      },
      deep: true
    },
    pageBuilder: {
      handler: function (value) {
        this.renderTable(this.filter, value)
      },
      deep: true
    }
  }
}
</script>

<style lang="less">
  .lab-applied-summary-sheet {
    @media (min-width: 1200px) {
      .btn-container {
        position: absolute;
        top: 0;
        right: 0;
        text-align: right;
      }
    }
    @media (min-width: 992px) {
      .btn-container {
        text-align: right;
      }
    }

    .btn-container {
      .export-btn {
        color: #19be6b;
        border-color: #19be6b;
        margin-left: 5px;
        margin-right: 5px;

        &:hover {
          color: #fff;
          background-color: #19be6b;
        }

        &:focus {
          box-shadow: unset;
        }
      }
    }

    .ivu-table {
      &-tbody {
        .ivu-table-cell {
          padding-top: 10px;
          padding-bottom: 10px;
          font-weight: bold;
        }
      }
      &-wrapper {
        border-color: #ccc;
      }
      &-border {
        & th {
          border-color: #ccc;
        }
        & td {
          border-color: #ccc;
        }
      }
    }
  }
</style>
